<?php

class url
{

    protected static $_segments;
    protected static $_string = '';
    protected static $_array;
    protected static $_num = 0;

    public function __construct()
    {
        self::initialize_segments();
    }

    protected static function initialize_segments()
    {

        switch (xiecx::config()->item('path_info'))
        {
            case 'AUTO':
                if ($_SERVER['PATH_INFO'] != '')
                {
                    self::$_string = $_SERVER['PATH_INFO'];
                }
                elseif ($_SERVER['QUERY_STRING'] != '')
                {
                    self::$_string = $_SERVER['QUERY_STRING'];
                }
                elseif ($_SERVER['REQUEST_URI'] != '')
                {
                    self::$_string = $_SERVER['REQUEST_URI'];
                }

                break;

            case 'PATH_INFO':
                self::$_string = $_SERVER['PATH_INFO'];
                break;

            case 'QUERY_STRING':
                self::$_string = $_SERVER['QUERY_STRING'];
                break;

            case 'REQUEST_URI':
                self::$_string = $_SERVER['REQUEST_URI'];
                break;

            default:
                xiecx::show_error('Could not set url string, pleace check the config', 'library', __CLASS__);
                break;
        }
        self::clean_segments();
    }

    protected static function clean_segments()
    {
        self::$_array = explode('/', trim(self::$_string, '/'));
        self::$_num = count(self::$_array);
        if (self::$_num > 0 && xiecx::config()->item('clean_url_segments') === TRUE)
        {
            if (!preg_match("|^[" . str_replace(array('\\-', '\-'), '-', preg_quote(xiecx::config()->item('premitted_url_chars'), '-')) . "]+$|i", implode('',self::$_array)))
            {
                xiecx::show_error('URL contains disallowed characters', 'library', __CLASS__);
            }
        }
    }

    public static function get_array()
    {
        return self::$_array;
    }
    
    public static function get_string()
    {
        return self::$_string;
    }
    
    public static function get_segement($i)
    {
        if($i < 1 or $i > self::$_num)
        {
            return false;
        }
        else
        {
            return self::$_array[--$i];
        }
    }
}